package ViewPhysAction;

use strict;

use Athena::WebAPI::Response;
use Athena::PhysView;
use Athena::Engine::Phys;

sub execute {
  my $stInvocant = shift(@_);
  my $rRequest = shift(@_);
  my $rConn = shift(@_);
  my %hParams = ( @_ );
  my $stParams = \%hParams;
  my $rResponse = undef;
  my $stErrMsg = "";
  my $stActionName = 'ViewPhysAction';
  $rRequest->action($stActionName);
  my $stAction = $rRequest->param($stActionName);
  my $stLb = $rRequest->cookie('AthenaEngineUrl') 
    || $rRequest->cookie('AthenaEngineHost') 
      . ":" . $rRequest->cookie('AthenaEnginePort');

  my $rHiddenFields = {
		       $rRequest->getActionParam() => $rRequest->action(),
		       $stActionName => '',
		      };

  # begin display pref handling 
  my @arShowCols = undef;
  if ($rRequest->param('show_cols')) {
    @arShowCols = $rRequest->param('show_cols');
    $rRequest->cookie('-name'=>'AthenaShowCols',
		      '-value'=>join(",", @arShowCols));
  }
  else {
    if ($rRequest->cookie('AthenaShowCols')) {
      @arShowCols = split(/,/, $rRequest->cookie('AthenaShowCols'));
    }
  } 

  # prefer params over cookie. reset cookie if params.
  my %hRenameCols = undef;
  if (@arShowCols) {
    my $key;
    my $stCkVal = undef;
    foreach $key (@arShowCols) {
      if ($rRequest->param('mv_col.' . $key)) {
	my $stName = $rRequest->param('mv_col.' . $key);
	$stName =~ s/,|=/ /g;
	$hRenameCols{$key} = $stName;
	if (defined ($stCkVal)) {
	  $stCkVal .= ",";
	}
	$stCkVal .= $key . "=" . $stName;
      }
    }
    if ($stCkVal) {
      $rRequest->cookie('-name'=>'AthenaMvCols', '-value'=>$stCkVal, 
			'-expires'=>'+1y');
    }
    elsif ($rRequest->cookie('AthenaMvCols')) {
      my $keyval;
      my @arMvCols = split(/,/, $rRequest->cookie('AthenaMvCols')); 
      for $keyval (@arMvCols) {
	my $val;
	($key, $val) = split(/=/, $keyval);
	$hRenameCols{$key} = $val;
      }
    }
  }
  # end display pref handling

  my $rPhyss = Athena::Engine::Phys->new($rConn);
  $rPhyss->refresh();
  my $rFarms = '0';
  # the ! case catches the default view, which contains farms
  if ((! @arShowCols) || (grep('farms', @arShowCols))) {
    $rFarms = Athena::Engine::Farm->new($rConn);
    $rFarms->refresh();
  }

  my $rView = PhysView->new('lb' => $stLb,
			    'physs' => $rPhyss,
			    'farms' => $rFarms,
			    'err_msg' => $stErrMsg,
			    'hidden_fields' => $rHiddenFields,
			    'action_name' => $stActionName,
			    'body_style' => $stParams->{body_style},
			    'table_style' => $stParams->{table_style},
			    'options' => $rRequest->param('options') || "0",
			    'show_cols' => \@arShowCols || "0",
			    'mv_cols' => \%hRenameCols || "0"
			   );

  $rResponse = Response->new($rView);
  
  return $rResponse;
}

1;
